package com.sxyc.tintin.controller;

import java.awt.image.BufferedImage;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;

import com.alibaba.fastjson.JSONObject;
import com.amitek.service.bean.protocol.PosInfo;
import com.amitek.service.bean.protocol.TrackInfo;
import com.amitek.service.bean.request.BindStatus;
import com.amitek.service.bean.request.DestInfo;
import com.amitek.service.bean.request.UploadType;
import com.amitek.service.bean.request.BindStatus.UserInfo;
import com.amitek.service.bean.response.TrackStatus;
import com.jfinal.kit.PropKit;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.CustomServiceApi;
import com.jfinal.weixin.sdk.api.CustomServiceApi.Articles;
import com.jfinal.weixin.sdk.api.MenuApi;
import com.jfinal.weixin.sdk.api.QrcodeApi;
import com.jfinal.weixin.sdk.api.TemplateData;
import com.jfinal.weixin.sdk.api.TemplateMsgApi;
import com.jfinal.weixin.sdk.api.UserApi;
import com.jfinal.weixin.sdk.jfinal.ApiController;
import com.sxyc.common.ImageRender;
import com.sxyc.common.LocalCache;
import com.sxyc.tintin.model.DeviceBinding;
import com.sxyc.tintin.model.WxUser;
import com.sxyc.tintin.sdk.SDKUtils;
import com.sxyc.utils.QMapUtils;
import com.sxyc.utils.ResultUtils;

public class CommonController extends ApiController {

	// 使用jFinal 日志
	private static com.jfinal.log.Log log = com.jfinal.log.Log.getLog(CommonController.class);

	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	/**
	 * 如果要支持多公众账号，只需要在此返回各个公众号对应的  ApiConfig 对象即可
	 * 可以通过在请求 url 中挂参数来动态从数据库中获取 ApiConfig 属性值
	 */
	public ApiConfig getApiConfig() {
		ApiConfig ac = new ApiConfig();
		
		// 配置微信 API 相关常量
		ac.setToken(PropKit.get("token"));
		ac.setAppId(PropKit.get("appId"));
		ac.setAppSecret(PropKit.get("appSecret"));
		
		/**
		 *  是否对消息进行加密，对应于微信平台的消息加解密方式：
		 *  1：true进行加密且必须配置 encodingAesKey
		 *  2：false采用明文模式，同时也支持混合模式
		 */
		ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
		ac.setEncodingAesKey(PropKit.get("encodingAesKey", "setting it in config file"));
		return ac;
	}
	
	/**
	 * 查询设备绑定状态
	 */
	public void userBindStatus() {
		String serviceId = getPara("serviceId");
		long deviceId = getParaToLong("deviceId");
		JSONObject jo = new JSONObject();
		try {
			WxUser user = WxUser.dao.getWxUserByDeviceId(deviceId);
			if (user != null) {
				jo.put("status", 1);
				jo.put("nickName", user.get("NickName"));
			} else {
				jo.put("status", 0);
			}
		} catch (Exception e) {
			jo.put("status", -1);
			jo.put("message", "查询设备 [ " + deviceId + " ] 绑定状态异常！");
			log.error("查询设备 [ " + deviceId + " ] 绑定状态异常，原因：" + e.getMessage());
		}
		renderJson(jo);
	}
	
	/**
	 * 获取设备相关联的二维码（如果未绑定）
	 */
	public void qrCode() {

		BufferedImage image = new BufferedImage(128, 128, BufferedImage.TYPE_INT_RGB);
		long deviceId = getParaToLong("deviceId");
		try {
			String qrCodeUrl = "";
			long timeout = 1000 * 3600 * 24 * 7;//单位：毫秒。 7天过期（暂时不考虑时间误差，如果后期考虑误差则适当的减小该值）
			Object cacheQrCodeUrl = LocalCache.getCache("qrCodeUrl", String.valueOf(deviceId));
			if (cacheQrCodeUrl != null && !"".equals(cacheQrCodeUrl)) {
				qrCodeUrl = (String) cacheQrCodeUrl;
			} else {
				Date nowDate = new Date();
				SimpleDateFormat sdf = new SimpleDateFormat("HHmmssSSS");
				int sceneId = Integer.parseInt(sdf.format(nowDate));
				int expireSeconds = (int) (timeout/1000);
				qrCodeUrl = getQrCodeUrl(expireSeconds, sceneId);

				// RedisUtils.setex(String.valueOf(sceneId), timeout,
				// deviceId);
				LocalCache.putCacheInfo("qrCodeUrl", String.valueOf(sceneId), deviceId, timeout);
				// RedisUtils.setex(String.valueOf(deviceId), timeout,
				// qrCodeUrl);
				LocalCache.putCacheInfo("qrCodeUrl", String.valueOf(deviceId), qrCodeUrl, timeout);
			}
			log.info("设备deviceId为 [ " + deviceId + " ] 的二维码Url = " + qrCodeUrl);
			URL imageUrl = new URL(qrCodeUrl);
			URLConnection connection = imageUrl.openConnection();
			connection.setDoOutput(true);
			image = ImageIO.read(connection.getInputStream());
		} catch (Exception e) {
			log.error("获取设备deviceId为 [ " + deviceId + " ] 的二维码异常，原因：" + e.getMessage());
		}
		ImageRender imageRender = new ImageRender(image);
		render(imageRender);
	}

	/**
	 * 接收并处理发送过来的告警数据
	 */
	public void alarmNotify() {
		log.info("alarmNotify 处理 ...");
		try {
			long deviceId = getParaToLong("deviceId");
			String openId = getPara("openId");
			long trackId = getParaToLong("trackId");
			String alarmType = getPara("alarmType");
			TrackStatus trackStatus = SDKUtils.getTrackStatus(deviceId, trackId);
			PosInfo posInfo = null;
			TrackInfo trackInfo = null;
			String address = "";
			Date alarmTime = new Date();
			String stopPic = "";
			if (trackStatus != null) {
				stopPic = trackStatus.stopPic;
				posInfo = trackStatus.posInfo;
				trackInfo = trackStatus.trackInfo;
			}else{
				log.info("未查询到设备 [ "+deviceId+" ] 的行程 ["+trackId+"] 信息!");
				renderJson(ResultUtils.getFailureResult("未查询到该设备的行程信息！"));
			}
			if(trackInfo!=null){
				alarmTime = new Date(trackInfo.gatherTime);
			}else{
				log.info("未查询到设备 [ "+deviceId+" ] 对应的行程 ["+trackId+"] 的行程信息!");
			}
			
			//如果没有位置信息，则在60S后重试获取
			if(posInfo == null){
				Thread.sleep(60*1000);
				posInfo = SDKUtils.getPosInfo(deviceId, trackId);
				log.info("未查询到设备 [ "+deviceId+" ] 对应的行程 ["+trackId+"] 的位置信息,60S后重试!");
			}
			if (posInfo != null) {
				double latitude = posInfo.latitude;
				double longitude = posInfo.longitude;
				// 调用百度或者腾讯地图获取位置信息
				address = QMapUtils.getAddress(latitude, longitude);
			}else{
				log.info("未查询到设备 [ "+deviceId+" ] 对应的行程 ["+trackId+"] 的位置信息（已尝试重新获取）!");
			}
			
			if (address == null || "".equals(address)) {
				address = "暂时无法获取地理位置信息";
			}
			String alarmTimeStr = sdf.format(alarmTime);
			
			 String title = "车辆告警";
			 String remark = "您的爱车有异常行为，如非您本人操作，请注意核实！";
			switch (alarmType) {
				case "shark":
					title = "车辆告警";
					remark = "您的爱车有异常行为，为了您的安全请检查车辆并文明驾驶！";
					break;
				case "start":
					title = "车辆启动";
					remark = "您的爱车已启动，若非本人操作请注意车辆安全!";
					break;
				case "stop":
					title = "车辆熄火";
					remark = "您的爱车已熄火，若非本人操作请注意车辆安全!";
					break;
			}
			
			// 发送微信模板消息
			ApiResult result = TemplateMsgApi.send(TemplateData.New().setTouser(openId)// 消息接收者
					.setTemplate_id(PropKit.get("alarm_template_id"))// 模板id
					.setTopcolor("#eb414a")
					.setUrl(stopPic)
					.add("first", title, "#222222")
					.add("keyword1", alarmTimeStr, "#000000")
					.add("keyword2", address, "#000000")
					//.add("keyword3", "", "#000000")
					.add("remark", remark, "#000000")
					.build());
			int errcode = result.getErrorCode();
			String errmsg = result.getErrorMsg();
			if (errcode == 0) {
				log.info("设备 [ "+deviceId+" ] 给微信 [ "+openId+" ] 发送告警信息成功！");
				renderJson(ResultUtils.getSuccessResult());
			} else {
				log.info("设备 [ "+deviceId+" ] 给微信 [ "+openId+" ] 发送告警信息失败！错误消息：" + errmsg);
				renderJson(ResultUtils.getFailureResult("模板消息发送失败！错误消息：" + errmsg));
			}
		} catch (Exception e) {
			log.error("alarmNotify Exception :" + e.getMessage());
			renderJson(ResultUtils.getFailureResult("告警消息发送异常！原因：" + e.getMessage()));
		}
	}

	/**
	 * 上传媒体文件
	 */
	public void uploadMedia(){
		log.info("uploadMedia ...");
		try {
			String fileUrl = getPara("fileUrl");
			String coverPic = getPara("coverPic");
			String openId = getPara("openId");
			int uploadType = getParaToInt("uploadType");
			String sessionId = getPara("sessionId");
			
			if(fileUrl!=null&&!"".equals(fileUrl)){
				String extension = fileUrl.substring(fileUrl.lastIndexOf(".")+1);
				String type = "";
				if("bmp".equalsIgnoreCase(extension)||"png".equalsIgnoreCase(extension)||"jpg".equalsIgnoreCase(extension)||"gif".equalsIgnoreCase(extension)){
					type = "image";
				}else if("amr".equalsIgnoreCase(extension)||"mp3".equalsIgnoreCase(extension)){
					type = "voice";
				}else if("mp4".equalsIgnoreCase(extension)){
					type = "video";
				}
				log.info("extension = "+extension+" ; type = "+type);
				
				Long deviceId = WxUser.dao.getDeviceIdByOpenId(openId);
				if(deviceId!=null){
					String address = SDKUtils.getAddress(deviceId);
					
					String title = "";
					String picUrl = "";
					
					
					String url=PropKit.get("root_url")+"/getWXPhone/getSuiPai?type="+type+"&openid="+openId+"&videoPic="+coverPic;
					if(type!=null&&!"".equals(type)){
						
						if(uploadType == UploadType.UPLOAD_TRACK.getValue()){
							title = "停车地址: "+address;
							picUrl = fileUrl;
							url="";
						}else{
							if("image".equals(type)){
								title = "随手拍: "+address;
								picUrl = fileUrl;
							}else if("video".equals(type)){
								title = "随手录: "+address;
								picUrl = coverPic;
							}
						}
						
						//发送客服-图文消息
						List<Articles> articles = new ArrayList<Articles>();
						Articles article1 = new Articles();
						article1.setTitle(sdf.format(new Date()));
						article1.setUrl(url);
						article1.setPicurl(picUrl);
						Articles article2 = new Articles();
						article2.setTitle(title);
						article2.setUrl("");
						article2.setPicurl("");
						articles.add(article1);
						articles.add(article2);
						ApiResult result = CustomServiceApi.sendNews(openId, articles);
						String resultStr = result.getJson();
						log.info("resultStr = "+resultStr);
						int errcode = result.getErrorCode();
						String errmsg = result.getErrorMsg();
						if (errcode == 0) {
							log.info("设备 [ "+deviceId+" ] 给微信 [ "+openId+" ] 发送文件成功！");
							renderJson(ResultUtils.getSuccessResult());
						} else {
							log.info("设备 [ "+deviceId+" ] 给微信 [ "+openId+" ] 发送文件失败！错误消息：" + errmsg);
							renderJson(ResultUtils.getFailureResult("接收文件失败！错误消息：" + errmsg));
						}
					}else{
						log.info("给微信 [ "+openId+" ] 发送文件失败，未知的文件类型！");
						renderJson(ResultUtils.getFailureResult("给微信 [ "+openId+" ]发送文件失败，未知的文件类型！"));
					}
				}else{
					//还未绑定设备
					log.info("给微信 [ "+openId+" ] 发送文件失败，还未绑定设备！");
					renderJson(ResultUtils.getFailureResult("给微信 [ "+openId+" ]发送文件失败，还未绑定设备！"));
				}
			}else{
				log.info("给微信 [ "+openId+" ] 发送文件失败,文件url不能为空！");
				renderJson(ResultUtils.getFailureResult("给微信 [ "+openId+" ] 发送文件失败,文件url不能为空！"));
			}
		} catch (Exception e) {
			log.error("uploadMedia Exception："+e.getMessage());
			renderJson(ResultUtils.getFailureResult("告警消息发送异常！原因：" + e.getMessage()));
		}
		
	}
	
	/**************************** 以下方法非Web请求方法 ******************************/
	
	/**
	 * 从微信生成临时二维码
	 * 
	 * @param expireSeconds
	 *            过期时间
	 * @param sceneId
	 *            场景Id
	 * @return 二维码Url地址
	 */
	private String getQrCodeUrl(int expireSeconds, int sceneId) {
		String qrCodeUrl = "";
		try {
			ApiResult createTemporary = QrcodeApi.createTemporary(expireSeconds, sceneId);
			String jsonStr = createTemporary.getJson();
			JSONObject jo = JSONObject.parseObject(jsonStr);
			String ticket = jo.get("ticket").toString();
			qrCodeUrl = QrcodeApi.getShowQrcodeUrl(ticket);
		} catch (Exception e) {
			log.error("获取二维码Url异常，原因：" + e.getMessage());
		}
		return qrCodeUrl;
	}

	/**
	 * 根据openId从微信服务器获取获得微信用户信息
	 * @param openId
	 * @return
	 */
	public static WxUser getWxUserByOpenId(String openId){
		WxUser user = null;
		try {
			ApiResult result = UserApi.getUserInfo(openId);
			if(result!=null){
				if (result.getJson() != null && !"".equals(result.getJson())) {
					JSONObject userOject = JSONObject.parseObject(result.getJson());
					String errcode = userOject.getString("errcode");
					String errmsg = userOject.getString("errmsg");
					if (errcode != null && !"".equals(errcode)) {
						log.info("获取微信用户信息失败！原因：" + errmsg);
					} else {
						String nickname = userOject.getString("nickname");
						int sex = userOject.getIntValue("sex");
						String city = userOject.getString("city");
						String country = userOject.getString("country");
						String province = userOject.getString("province");
						String headimgurl = userOject.getString("headimgurl");
						String subscribe = userOject.getString("subscribe");
						long subscribe_time = userOject.getLong("subscribe_time");
						String unionid = userOject.getString("unionid");
						String remark = userOject.getString("remark");
						String groupid = userOject.getString("groupid");
						String tagid_list = userOject.getString("tagid_list");

						user = new WxUser();
						user.set("AppID", PropKit.get("appId"));
						user.set("NickName", nickname);
						user.set("Sex", sex);
						user.set("City", city);
						user.set("Country", country);
						user.set("Province", province);
						user.set("HeadImgUrl", headimgurl);
						user.set("Subscribe", subscribe);
						user.set("SubscribeTime", new Date(subscribe_time));
						user.set("Unionid", unionid);
						user.set("Remark", remark);
						user.set("GroupId", groupid);
						user.set("TagidList", tagid_list);
						user.set("UpdatedBy", "System");
						user.set("UpdatedDate", new Date());
					}
				}
			}else{
				log.info("获取微信用户信息返回为空！");	
			}
		} catch (Exception e) {
			log.error("获取微信用户信息异常，原因："+e.getMessage());
		}
		return user;
	}
	
	/**
	 * 将设备绑定到微信
	 * @param openId
	 * @param sceneId
	 * @return
	 */
	public static int binding(String openId,String sceneId){
		String message = "";
		int code;
		try {
			long deviceId = (long) LocalCache.getCache("qrCodeUrl", sceneId);
			WxUser user = WxUser.dao.getWxUserByDeviceId(deviceId);
			if (user != null) {
				log.info("设备 [ " + deviceId + " ] 已经绑定其他微信，暂时无法绑定！");
				message = ("该设备已经绑定其他微信，暂时无法绑定！");
				code=0;
			} else {
				log.info("设备 [ " + deviceId + " ] 还未绑定微信！");
				user = WxUser.dao.getWxUser(openId);
				boolean isSuccess = false;
				if (user != null) {
					user.set("DeviceId", deviceId);
					//user.set("BindingTime", new Date());
					isSuccess = user.update();
				} else {
					user = CommonController.getWxUserByOpenId(openId);
					if (user == null) {
						user = new WxUser();
					}
					user.set("AppID", PropKit.get("appId"));
					user.set("OpenId", openId);
					user.set("DeviceId", deviceId);
					//user.set("BindingTime", new Date());
					user.set("Subscribe", "1");
					user.set("SubscribeTime", new Date());
					user.set("Status", 1);
					user.set("CreatedBy", "System");
					user.set("CreatedDate", new Date());
					user.set("UpdatedBy", "System");
					user.set("UpdatedDate", new Date());
					isSuccess = user.save();
				}
				if (isSuccess) {
					log.info("设备 [ " + deviceId + " ] 绑定微信 [ " + openId + " ] 成功");
					
					//给设备下发绑定状态
					SDKUtils.sendBindStatus(deviceId);
					//清除绑定历史信息
					DeviceBinding.dao.clearDeviceBinding(openId);
					//更新绑定关联表
					DeviceBinding.dao.addDeviceBinding(deviceId, openId);
					
					message = ("该设备已经成功绑定微信！");
					code=1;
				} else {
					log.info("设备 [ " + deviceId + " ] 绑定微信 [ " + openId + " ] 失败");
					message = ("该设备绑定微信失败，请重新绑定！");
					code=2;
				}
			}
		} catch (Exception e) {
			log.error("设备绑定到微信异常！原因：" + e.getMessage());
			code=3;
			message = ("该设备绑定微信失败，请重新绑定！");
		}
		System.out.println("code---->"+code);
		return code;
	}
	
	/**
	 * 解绑微信
	 * @param openId
	 * @return
	 */
	public static String unBinding(String openId){
		String message = "";
		try {
			WxUser user = WxUser.dao.getWxUser(openId);
			if(user!=null){
				Long deviceId = user.get("DeviceId");
				if(deviceId!=null){
					user.set("DeviceId", null);
					user.set("UpdatedBy", "System");
					user.set("UpdatedDate", new Date());
//					System.out.println("deviceId后---->"+user.getLong("DeviceId"));
					boolean isSuccess = user.update();
					if(isSuccess){
						log.info("微信 [ "+openId+" ] 解绑设备 [ "+deviceId+" ] 成功！");
						BindStatus bindStatus = new BindStatus();
						bindStatus.bindStatus = false;
						UserInfo userInfo = new UserInfo();
						userInfo.openId = openId;
						userInfo.nickName = "";
						bindStatus.weixin = userInfo;
						SDKUtils.sendBindStatus(deviceId, bindStatus);
						//更新绑定关联表
						try {
							DeviceBinding.dao.deleteDeviceBinding(deviceId, openId);
						} catch (Exception ex) {
							log.error("更新设备 [ " + deviceId + " ] 绑定微信 [ " + openId + " ] 关联关系异常！原因："+ex.getMessage());
						}
						
						message = "解绑成功！";
					}else{
						message = "解绑失败，请重试！";
					}
				}else{
					log.info("微信 [ "+openId+" ] 还未绑定设备！");
					message = "您还未绑定设备！";
				}
			}else{
				log.info("微信 [ "+openId+" ] 还未绑定设备，忽略解绑请求！");
				message = "您还未绑定设备，解绑请求无效！";
			}
		} catch (Exception e) {
			log.info("微信 [ "+openId+" ] 解绑异常！原因："+e.getMessage());
			message = "解绑出现问题，请重试！";
		}
		return message;
	}
	
	/**
	 * 发送设备最后状态（微信找车）
	 * @param openId 微信唯一标识
	 * @return
	 */
	public static String sendDeviceStatus(String openId){
		String message = "";
		try {
			Long deviceId = WxUser.dao.getDeviceIdByOpenId(openId);
			if(deviceId!=null){
				TrackStatus trackStatus = SDKUtils.getLastTrackStatus(deviceId);
				PosInfo posInfo = null;
				TrackInfo trackInfo = null;
				String address = "";
				Date lastTime = new Date();
				String stopPic = "";
				String lastTimeStr = "";
				if (trackStatus != null) {
					stopPic = trackStatus.stopPic;
					posInfo = trackStatus.posInfo;
					trackInfo = trackStatus.trackInfo;
					if(trackInfo!=null){
						lastTime = new Date(trackInfo.gatherTime);
					}else{
						log.info("未查询到设备 [ "+deviceId+" ] 的最后行程信息!");
					}
					if (posInfo != null) {
						double latitude = posInfo.latitude;
						double longitude = posInfo.longitude;
						// 调用百度或者腾讯地图获取位置信息
						address = QMapUtils.getAddress(latitude, longitude);
					}else{
						log.info("未查询到设备 [ "+deviceId+" ] 最后的位置信息!");
					}
					
					if (address == null || "".equals(address)) {
						address = "暂时无法获取地理位置信息";
					}
					lastTimeStr = sdf.format(lastTime);
					
					//如果都为空
					if("".equals(address)&&"".equals(lastTimeStr)&&"".equals(stopPic)){
						log.info("查询到设备的最后行程信息 [ 地点、时间、图片  ] 均为空!");
						message = "未查询到该设备的最后行程信息！";
					}else{
						message = "【您的爱车最新信息】\n 位置："+address+" \n 时间："+lastTimeStr +" \n 图片："+stopPic;
//						this.setAttr("address", address);
//						this.setAttr("lastTimeStr", lastTimeStr);
//						this.setAttr("stopPic", stopPic);
						//TODO 发送模板消息
						ApiResult result = TemplateMsgApi.send(TemplateData.New().setTouser(openId)// 消息接收者
								.setTemplate_id(PropKit.get("alarm_template_id"))// 模板id
								.setTopcolor("#eb414a")
								.setUrl(stopPic)
								.add("first", "车辆最后位置\n", "#222222")
								.add("keyword1", lastTimeStr, "#000000")
								.add("keyword2", address, "#000000")
								.add("keyword3", "点击可以查看车辆最后位置和图片", "#000000")
								.add("remark", "", "#000000")
								.build());
						int errcode = result.getErrorCode();
						String errmsg = result.getErrorMsg();
						if (errcode == 0) {
							log.info("设备 [ "+deviceId+" ] 给微信 [ "+openId+" ] 发送最后位置信息成功！");
						} else {
							log.info("设备 [ "+deviceId+" ] 给微信 [ "+openId+" ] 发送最后位置信息失败！错误消息：" + errmsg);
						}
					}
				}else{
					log.info("未查询到设备 [ "+deviceId+" ] 的最后行程信息!");
					message = "未查询到该设备的最后行程信息！";
				}
			}else{
				log.info("微信 [ "+openId+" ] 还未绑定设备!");
				message = "您还未绑定设备！";
			}
		} catch (Exception e) {
			log.error("查找微信 [ "+openId+" ] 绑定的设备最后状态异常，原因："+e.getMessage());
			message = "查找设备最后状态失败，请重试！";
		}
		/*this.setAttr("message", message);
		renderJsp("findCar.jsp");*/
		return message;
	}

	/**
	 * 获取图片（随拍）
	 * @param openId
	 * @return
	 */
	public static String getPhoto(String openId){
		String message = "";
		try {
			Long deviceId = WxUser.dao.getDeviceIdByOpenId(openId);
			if(deviceId!=null){
				int mediaType = 0;//媒体文件类型：0:图片 1:视频 2:音频
				int uploadType = 1;//上传类型 ： 0:行程结束图片 1:分享 2:监控 3:报警 4:其他
				int uploadCnt = 1;//请求上传的的文件参数. 对应图片，为上传图片数量；对应视频/音频，为上传视频/音频时间的秒数
				boolean isSuccess = SDKUtils.requestMedia(deviceId, mediaType, uploadType, uploadCnt);
				if(isSuccess){
					log.info("微信["+openId+"]发送随拍指令成功！");
					message = "图片抓拍中, 请稍后...";
				}else{
					log.info("微信["+openId+"]发送随拍指令失败！");
					message = "发送随拍指令失败！";
				}
			}else{
				message = "您还没有绑定微信！";
			}
		} catch (Exception e) {
			log.info("getPhoto Exception："+e.getMessage());
			message = "发送随拍指令异常！";
		}
		return message;
	}
	
	/**
	 * 获取视频（随录）
	 * @param openId
	 * @return
	 */
	public static String getVideo(String openId){
		String message = "";
		try {
			Long deviceId = WxUser.dao.getDeviceIdByOpenId(openId);
			if(deviceId!=null){
				int mediaType = 1;//媒体文件类型：0:图片 1:视频 2:音频
				int uploadType = 1;//上传类型 ： 0:行程结束图片 1:分享 2:监控 3:报警 4:其他
				int uploadCnt = 6;//请求上传的的文件参数. 对应图片，为上传图片数量；对应视频/音频，为上传视频/音频时间的秒数
				boolean isSuccess = SDKUtils.requestMedia(deviceId, mediaType, uploadType, uploadCnt);
				if(isSuccess){
					log.info("微信["+openId+"]发送随录指令成功！");
					message = "视频录取中, 请稍后...";
				}else{
					log.info("微信["+openId+"]发送随录指令失败！");
					message = "发送随录指令失败！";
				}
			}else{
				message = "您还没有绑定微信！";
			}
		} catch (Exception e) {
			log.info("getVideo Exception："+e.getMessage());
			message = "发送随录指令异常！";
		}
		return message;
	}

	/**
	 * 执行导航操作
	 * @param openId
	 * @param address
	 * @param latitude
	 * @param longitude
	 * @return
	 */
	public static int navigate(String openId,String address,double longitude,double latitude){
		String message = "";
		int code;
		try {
			Long deviceId = WxUser.dao.getDeviceIdByOpenId(openId);
			if(deviceId!=null){
				DestInfo destInfo = new DestInfo();
				destInfo.address = address;
				destInfo.latitude = latitude;
				destInfo.longitude = longitude;
				boolean isSuccess = SDKUtils.requestNavigate(deviceId, null,destInfo);
				if(isSuccess){
					log.info("微信["+openId+"]发送导航指令成功！");
					message = "发送成功！";
					code=200;
				}else{
					log.info("微信["+openId+"]发送导航指令失败！");
					message = "发送导航指令失败！";
					code=202;
				}
			}else{
				message = "您还没有绑定微信！";
				code=401;
			}
		} catch (Exception e) {
			log.info("getVideo Exception："+e.getMessage());
			message = "发送导航指令异常！";
			code=500;
		}
		return code;
	}

	/**
	 * 显示报警信息
	 * @param openId
	 * @param content
	 * @return
	 */
	public static String showAlert(String openId,String[] content){
		String message = "";
		try {
			Long deviceId = WxUser.dao.getDeviceIdByOpenId(openId);
			if(deviceId!=null){
				String[] paramName = null;
				String[] paramValue = content;
				boolean isSuccess = SDKUtils.requestShowAlert(deviceId, paramName,paramValue);
				if(isSuccess){
					log.info("微信["+openId+"]发送显示报警信息指令成功！");
					message = "正在显示报警信息, 请稍后...";
				}else{
					log.info("微信["+openId+"]发送显示报警信息指令失败！");
					message = "发送显示报警信息指令失败！";
				}
			}else{
				message = "您还没有绑定微信！";
			}
		} catch (Exception e) {
			log.info("getVideo Exception："+e.getMessage());
			message = "发送显示报警信息指令异常！";
		}
		return message;
	}
	
	/**
	 * 创建菜单
	 */
	public void createMenu() {
		String str = 
				"{\"button\": [" +
					"{" +
						"\"name\": \"在路上\"," +
						"\"sub_button\":[" +
						    "{" +
						     	"\"type\":\"click\"," +
						     	"\"name\":\"图片抓拍\"," +
						    	"\"key\":\"photo\"" +
						    "}," +
						    "{" +
						       	"\"type\":\"click\"," +
						     	"\"name\":\"视频抓拍\"," +
						     	"\"key\":\"video\"" +
							"}," +
						    "{" +
						       	"\"type\":\"view\"," +
						     	"\"name\":\"我的排行\"," +
						    	"\"url\":\""+ PropKit.get("domain") +"/person/getPaihang\"" +
							"}," +
							"{" +
						       	"\"type\":\"view\"," +
						     	"\"name\":\"驾驶分析\"," +
						    	"\"url\":\""+ PropKit.get("domain") +"/person/getDrivings\"" +
							"}," +
						    "{" +
						     	"\"type\":\"view\"," +
						     	"\"name\":\"轨迹查询\"," +
						     	"\"url\":\""+ PropKit.get("domain") +"/track\"" +
						    "}]" +
					"},{" +
						"\"name\": \"车管家\"," +
						 "\"sub_button\":[" +
						    "{" +
						     	"\"type\":\"view\"," +
						     	"\"name\":\"微信找车\"," +
						     	"\"url\":\""+ PropKit.get("domain") +"/findcar\"" +
						    "}," +
						    "{" +
						       	"\"type\":\"view\"," +
						     	"\"name\":\"流量充值\"," +
						    	"\"url\":\""+ PropKit.get("domain") +"/pay/wxchongzhi\"" +
							"}," +
							"{" +
						       	"\"type\":\"view\"," +
						     	"\"name\":\"违章查询\"," +
						     	"\"url\":\""+ PropKit.get("domain") +"/template/juheQuery\"" +
					     	"}," +
							"{" +
						       	"\"type\":\"view\"," +
						     	"\"name\":\"维修快保\"," +
						     	"\"url\":\""+ PropKit.get("domain") +"/person/repair\"" +
							"}," +
						    "{" +
								"\"type\":\"view\"," +
						     	"\"name\":\"油卡充值\"," +
						        "\"url\":\"http://wximg.qq.com/cityservices/3rd/html/jiayouka.html\"" +
							"}]" +
					"},{" +
						"\"name\": \"我的叮当\"," +
						 "\"sub_button\":[" +
							"{" +
						       	"\"type\":\"view\"," +
						     	"\"name\":\"设备信息\"," +
						    	"\"url\":\""+ PropKit.get("domain") +"/UnBind\"" +
							"}," +
						    "{" +
						     	"\"type\":\"click\"," +
						     	"\"name\":\"操作指导\"," +
						     	"\"key\":\"instruction\"" +
						    "}," +
						    "{" +
						     	"\"type\":\"view\"," +
						     	"\"name\":\"问题反馈\"," +
						     	 "\"url\":\""+ PropKit.get("domain") +"/wx/jsp/feedback.jsp\"" +
						    "}," +
						    "{" +
						     	"\"type\":\"view\"," +
						     	"\"name\":\"云端商城\"," +
						     	 "\"url\":\""+ PropKit.get("domain") +"/person/cloud\"" +
						    "}," +
						    "{" +
						       	"\"type\":\"view\"," +
						     	"\"name\":\"导航指导\"," +
						     	"\"url\":\""+ PropKit.get("domain") +"/wx/html/huoyunmap.html\"" +
							"}]" +
					"}" +
				"]}";
		
		System.out.println(str);
		ApiResult apiResult = MenuApi.createMenu(str);
		System.out.println("ok : " + apiResult);
		if (apiResult.isSucceed())
			renderText(apiResult.getJson());
		else
			renderText(apiResult.getErrorMsg());
	}

	/**
	 * 删除菜单
	 */
	public void deleteMenu() {
		renderJson(MenuApi.deleteMenu());
	}
	
	/**
	 * 创建个性化菜单
	 */
	public void createJiaKeMenu() {
		String str = 
				"{\"button\": [" +
					"{" +
						"\"name\": \"车生活\"," +
						"\"sub_button\":[" +
						    "{" +
						     	"\"type\":\"view\"," +
						     	"\"name\":\"任务领取\"," +
						        "\"url\":\"http://wx.xajiake.com\"" +
						    "}," +
						    "{" +
						       	"\"type\":\"view\"," +
						     	"\"name\":\"限量保养\"," +
						     	"\"url\":\"http://mp.weixin.qq.com/s/-m_jDufffay4tqaab_PgoA\"" +
							"}," +
						    "{" +
						       	"\"type\":\"click\"," +
						     	"\"name\":\"广告投放\"," +
						     	"\"key\":\"advert\"" +
							"}," +
						    "{" +
						     	"\"type\":\"view\"," +
						     	"\"name\":\"车险大促\"," +
						        "\"url\":\"http://mp.weixin.qq.com/s/zVGxN_Bn7lY9afOaHoFocg\"" +
						    "}]" +
					"},{" +
						"\"name\": \"我\"," +
						 "\"sub_button\":[" +
						    "{" +
						     	"\"type\":\"click\"," +
						     	"\"name\":\"我的任务\"," +
						     	"\"key\":\"new\"" +
						    "}," +
						    "{" +
						       	"\"type\":\"click\"," +
						     	"\"name\":\"我的积分\"," +
						     	"\"key\":\"new\"" +
							"}," +
						    "{" +
								"\"type\":\"view\"," +
						     	"\"name\":\"会员认证\"," +
						        "\"url\":\"http://wx.xajiake.com/pages/user/user-authentication.html\"" +
							"}]" +
					"},{" +
						"\"name\": \"我的服务\"," +
						 "\"sub_button\":[" +
						    "{" +
						     	"\"type\":\"click\"," +
						     	"\"name\":\"图片抓拍\"," +
						     	"\"key\":\"photo\"" +
						    "}," +
						    "{" +
						       	"\"type\":\"click\"," +
						     	"\"name\":\"视频抓拍\"," +
						     	"\"key\":\"video\"" +
							"}," +
							"{" +
						     	"\"type\":\"view\"," +
						     	"\"name\":\"行驶轨迹\"," +
						     	"\"url\":\""+ PropKit.get("domain") +"/track\"" +
						    "}," +
						    "{" +
						       	"\"type\":\"view\"," +
						     	"\"name\":\"微信找车\"," +
						     	"\"url\":\""+ PropKit.get("domain") +"/findcar\"" +
							"}," +
							"{" +
						       	"\"type\":\"view\"," +
						     	"\"name\":\"系统设置\"," +
						     	"\"url\":\""+ PropKit.get("domain") +"/pay/wxchongzhi\"" +
							"}]" +
					"}" +
				"]}";
		
		System.out.println(str);
		ApiResult apiResult = MenuApi.createMenu(str);
		System.out.println("ok : " + apiResult);
		if (apiResult.isSucceed())
			renderText(apiResult.getJson());
		else
			renderText(apiResult.getErrorMsg());
	}
	
	
	
}
